import View from './View'
import Img from './Img'

class CV {
    constructor(ctx, width, height) {
        this.ctx = ctx
        const options = {
            x: 0,
            y: 0,
            width: width,
            height: height
        }
        this.props = this.style = options
        this.children = []
    }
    view(options) {
        const view = new View()
        options = options || {}
        for (let k in options) {
            if (view.hasOwnProperty(k)) {
                view.style[k] = options[k]
            }
        }
        return view
    }
    img(options) {
        const img = new Img(options.src)
        options = options || {}
        for (let k in options) {
            if (k !== 'src' && img.hasOwnProperty(k)) {
                img.style[k] = options[k]
            }
        }
        return img
    }
    //addChild
    add(child) {
        if (child.render && child.tag) {
            child.parent = this
            child.update()
            this.remove(child)
            this.children.push(child)
        }
    }
    remove(child) {
        for (let i = 0, len = this.children.length; i < len; i++) {
            if (this.children[i] === child) {
                this.children.splice(i, 1)
                break;
            }
        }
    }
    clear() {
        this.children.splice(0, this.children.length)
    }
    render() {
        if(!this.ctx) return
        this.ctx.clearRect(0, 0, this.width, this.height)
        for (let i = 0, len = this.children.length, child = null; i < len; i++) {
            child = this.children[i]
            if (child.render) child.render(this.ctx)
        }
        // this.ctx.fill()
        // this.ctx.stroke()
        // this.ctx.draw()
    }
}

export default CV